package com.xingyun.info_manager.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.xingyun.info_manager.entity.AdminUser;
import com.xingyun.info_manager.entity.ParasBean;
import com.xingyun.info_manager.entity.ReturnBeans;
import com.xingyun.info_manager.service.IAdminUserService;
import com.xingyun.info_manager.util.JSONChange;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @Classname AdminController
 * @Description 用户信息
 * @Date 2020/5/18 10:42
 * @Created by You
 */
@Controller
public class AdminController {
    @Autowired
    private IAdminUserService adminUserService;

    /**
     * 查询所有用户信息
     */
//    @RequestMapping("/admin/findall")
//    public String findAllUser(HttpServletRequest request){
//        List<AdminUser> adminList =  adminUserService.findAllUser();
//        request.setAttribute("adminList",adminList);
//        return "admin/admin_list_demo";
//    }

    /**
     * 查询所有登录用户信息
     */
    @ResponseBody
    @RequestMapping("/admin/findall")
    public String findAllUserDemo(HttpServletRequest request, HttpSession session) throws JsonProcessingException {
        String userName = request.getParameter("userName");
        String realName = request.getParameter("realName");
        String userMobile = request.getParameter("userMobile");

        //获取登录用户信息，从session中取出
        AdminUser admin = (AdminUser) session.getAttribute("admin");
        //获取渠道id
        int channelId = admin.getChannelId();

        //用于传参实体类
        ParasBean parasBean = new ParasBean();
        parasBean.setChannelId(channelId);
        parasBean.setUserName(userName);
        parasBean.setRealName(realName);
        parasBean.setUserMobile(userMobile);

        Integer currPage;//当前页数
        if(!StringUtils.isBlank(request.getParameter("currPage"))) {
            currPage = Integer.valueOf(request.getParameter("currPage"));
        } else {
            currPage = 1;
        }
        parasBean.setCurrPage(currPage);

        Integer pageSize;//每页展示条数
        if(!StringUtils.isBlank(request.getParameter("pageSize"))) {
            pageSize = Integer.valueOf(request.getParameter("pageSize"));
        } else {
            pageSize = 5;
        }
        parasBean.setPageSize(pageSize);
        //返回的响应对象
        ReturnBeans<List<AdminUser>> returnBean = new ReturnBeans<List<AdminUser>>();
        returnBean.setCurrPage(currPage);
        returnBean.setPageSize(pageSize);
        //根据页数和显示条数计算分页起始位置
        int initPage = (currPage - 1) * pageSize;
        parasBean.setInitPage(initPage);

        /**
         * 查询总条数
         */
        int count = adminUserService.findCount(parasBean);
        returnBean.setCount(count);
        System.out.println("------ "+initPage+","+pageSize+","+count);

        /**
         * 查询详细信息
         */
        List<AdminUser> adminList =  adminUserService.findAllUser(parasBean);
//        request.setAttribute("adminList",adminList);
        returnBean.setData(adminList);
        request.setAttribute("page",returnBean);
        System.out.println(" - --" + JSONChange.objToJson(returnBean));
        //将对象转为json字符串返回
        return JSONChange.objToJson(returnBean);
    }


    /**
     * 新增
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @ResponseBody
    @RequestMapping("/admin/add")
    public String addAdmin(HttpServletRequest request, HttpSession session) throws JsonProcessingException {

        AdminUser adminUser = new AdminUser();
        adminUser.setUserName(request.getParameter("userName"));
        adminUser.setUserPwd(request.getParameter("userPwd"));
        System.out.println(request.getParameter("userPwd")+"-----------" + request.getParameter("userName"));
        adminUser.setRealName(request.getParameter("realName"));
        adminUser.setUserMobile(request.getParameter("userMobile"));
        adminUser.setPosition(request.getParameter("position"));
        adminUser.setRoleId(Integer.parseInt(request.getParameter("roleId")));
        adminUser.setChannelId(Integer.parseInt(request.getParameter("channelId")));

        System.out.println("-----------" + adminUser);
        //获取登录用户信息
        AdminUser admin = (AdminUser) session.getAttribute("admin");
        //获取创建人登录名
        adminUser.setCreateName(admin.getUserName());
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取创建时间
        adminUser.setCreateTime(new Date());

        //返回的响应对象
        ReturnBeans returnBean = new ReturnBeans<>();

        int res = adminUserService.addAdmin(adminUser);
        if(res == 0){
            returnBean.setCode(1);
            returnBean.setMsg("新增失败");
        }
        //将对象转为json字符串返回
        return JSONChange.objToJson(returnBean);
    }

    /**
     * 跳转到修改页
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/admin/toUpdate")
    public String toUpdatePage(HttpServletRequest request) {
        //获取user_id
        int id = Integer.parseInt(request.getParameter("userId"));
        //根据用户id查询用户信息
        AdminUser adminUser = adminUserService.findById(id);
        request.setAttribute("adminUser",  adminUser);

        //跳转到修改页面
        return "admin/admin_update";
    }

    /**
     * 修改
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @ResponseBody
    @RequestMapping("/admin/update")
    public String updateAdmin(HttpServletRequest request, HttpSession session) throws JsonProcessingException {

        AdminUser adminUser = new AdminUser();
        adminUser.setUserId(Integer.parseInt(request.getParameter("userId")));
        adminUser.setUserName(request.getParameter("userName"));
        adminUser.setUserPwd(request.getParameter("userPwd"));
        System.out.println(request.getParameter("userPwd")+"-----------" + request.getParameter("userName"));
        adminUser.setRealName(request.getParameter("realName"));
        adminUser.setUserMobile(request.getParameter("userMobile"));
        adminUser.setChannelId(Integer.parseInt(request.getParameter("channelId")));
        adminUser.setRoleId(Integer.parseInt(request.getParameter("roleId")));

        System.out.println("-----------" + adminUser);
//        //获取登录用户信息
//        AdminUser admin = (AdminUser) session.getAttribute("admin");
//        //获取创建人登录名
//        adminUser.setCreateName(admin.getUserName());
////        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        //获取创建时间
//        adminUser.setCreateTime(new Date());

        //返回的响应对象
        ReturnBeans returnBean = new ReturnBeans<>();

        int res = adminUserService.updateAdmin(adminUser);
        if(res == 0){
            returnBean.setCode(1);
            returnBean.setMsg("修改失败");
        }
        //将对象转为json字符串返回
        return JSONChange.objToJson(returnBean);
    }


    /**
     * 修改用户状态：启用/禁用
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @ResponseBody
    @RequestMapping("/admin/chgstate")
    public String changeState(HttpServletRequest request, HttpSession session) throws JsonProcessingException {

        AdminUser adminUser = new AdminUser();
        adminUser.setUserId(Integer.parseInt(request.getParameter("userId")));
        //当前用户状态
        int userState = Integer.parseInt(request.getParameter("userState"));
        if(userState == 1){
            userState = 2;//修改后用户状态（2，禁用、1：启用）
        } else {
            userState = 1;//修改后用户状态（2，禁用、1：启用）
        }
        adminUser.setUserState(userState);
        System.out.println("-----------" + adminUser);

        //返回的响应对象
        ReturnBeans returnBean = new ReturnBeans<>();

        int res = adminUserService.changeState(adminUser);
        if(res == 0){
            returnBean.setCode(1);
            returnBean.setMsg("修改失败");
        }
        //将对象转为json字符串返回
        return JSONChange.objToJson(returnBean);
    }

    /**
     * 删除
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @ResponseBody
    @RequestMapping("/admin/del")
    public String delAdmin(HttpServletRequest request, HttpSession session) throws JsonProcessingException {

        int userId = Integer.parseInt(request.getParameter("userId"));

        //返回的响应对象
        ReturnBeans returnBean = new ReturnBeans<>();

        int res = adminUserService.delAdmin(userId);
        if(res == 0){
            returnBean.setCode(1);
            returnBean.setMsg("删除失败");
        }
        //将对象转为json字符串返回
        return JSONChange.objToJson(returnBean);
    }

    /**
     * 根据用户名和渠道号查询用户是否存在
     * 在新增和修改时需要判断
     */
    @ResponseBody
    @RequestMapping("/admin/isExist")
    public String getInfoByAdminChannelNo(HttpServletRequest request) throws JsonProcessingException {
        //获取登录用户userName
        String userName = request.getParameter("userName");
        //获取登录用户channelId
        int channelId = Integer.parseInt(request.getParameter("channelId"));

        //获取id(id=0时为新增查询过滤不处理，id!=0时为修改过滤，需处理)
        int userId = Integer.parseInt(request.getParameter("userId"));

        //返回的响应对象
        ReturnBeans returnBean = new ReturnBeans<>();

        int res = adminUserService.getInfoByAdminChannelNo(userName,channelId,userId);
        if(res > 0){
            returnBean.setCode(1);
            returnBean.setMsg("此渠道用户已存在!");
        }
        //将对象转为json字符串返回
        return JSONChange.objToJson(returnBean);
    }

    /**
     * 跳转个人基本信息页面
     * @param session
     * @return
     */
    @RequestMapping("/admin/selfinfo")
    public String selfInfo(HttpSession session){
        //直接跳转到信息页面从session中获取值
        return "admin/self_info";
    }

}
